package cn.wolfcode.trip.app.webSocket;

import lombok.Getter;
import lombok.Setter;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

@Getter@Setter
@ServerEndpoint("/socket/listen")
public class ListenSocket {

    //发起私信提醒的静态方法
    public static void push(Long user1Id,Long user2Id){
        if (users.size() > 0) {
            for (ListenSocket user : users) {
                if (user.getId() == user2Id) {
                    String msg = "listen&" + user1Id + "&" + user2Id;
                    try {
                        user.session.getBasicRemote().sendText(msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    private static final Set<ListenSocket> users = new CopyOnWriteArraySet<>();
    Session session;
    //被监听用户的id
    private Long id;
    //建立连接
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("监听中..");
    }

    //断开连接
    @OnClose
    public void onClose() {
        System.out.println("监听中止");
        users.remove(this);
    }
    //客户端传来的信息
    @OnMessage
    public void onMessage(String msg) throws Exception{
        id = Long.valueOf(msg);
        users.add(this);
    }
}
